<template>
  <view class="page">
    <!-- 流程查询区域 -->
    <view>
      <wd-search v-model="queryForm.QueryValue" placeholder-left hide-cancel @search="getFlowInstancePages">
        <template #prefix>
          <wd-popover mode="menu" :content="filterOptions" @menuclick="menuclick">
            <view class="search-type">
              <text class="search-type">{{ queryForm.QueryLabel }}</text>
              <wd-icon custom-class="icon-arrow" name="fill-arrow-down"></wd-icon>
            </view>
          </wd-popover>
        </template>
      </wd-search>
    </view>
    <!-- 流程实例区域 -->
    <view class="pt-2" v-show="flowInstanceList.length">
      <view class="mb12" v-for="(item, index) in flowInstanceList" :key="index">
        <wd-card title="流程信息">
          <span>当前进度: {{ item.CurrentNodeName }}</span>
          <wd-progress :percentage="item.progressPercentage" />
          <template #footer>
            <wd-button size="small" plain @click="goToDetailPage(item)">去处理</wd-button>
          </template>
        </wd-card>
      </view>
    </view>
    <view v-show="!flowInstanceList.length">
      <wd-status-tip image="content" tip="暂无内容" />
    </view>
    <!-- 分页 -->
    <view>
      <wd-pagination
        v-model="pagination.currentPage"
        :total="pagination.total"
        :page-size="pagination.pageSize"
      />
    </view>
  </view>
</template>

<script setup lang="ts">
import { flowinstancePages, flowtemplateQueryFilterList } from '@/service/index/flow'
import { reactive, ref } from 'vue'
import { useToast } from 'wot-design-uni/components/wd-toast'

const pagination = reactive<any>({
  total: 0,
  pageSize: 10,
  currentPage: 1,
})

// 存储动态表单项
const formLabels = ref([])
// const formList = ref([]);
const filterOptions = ref([])
const flowInstanceList = ref([])
const toast = useToast()
// 接收参数
const props = defineProps(['flowType'])

/* 查询表单 */
const queryForm = reactive({
  QueryLabel: '全部',
  QueryValue: '',
})
/* Flow Type 映射关系 */
const flowTypeMap = {} // '造价类','代理类', '监理类'

/* 获取查询条件 */
const getFiterList = () => {
  flowtemplateQueryFilterList({FlowType: props.flowType}).then((rsp) => {
    if (rsp.IsSuccess) {
      filterOptions.value = rsp.Data?.map((v) => {
        return {
          content: v,
        }
      })
    } else {
      toast.error(rsp.ErrorMsg)
    }
  })
}

/** 获取当前流程实例列表 **/
const getFlowInstancePages = () => {
  flowinstancePages({
    PageSize: 10,
    PageNo: 1,
    QueryLabel: queryForm.QueryLabel === '全部'? '': queryForm.QueryLabel,
    QueryValue: queryForm.QueryValue,
    OrderByLabel: '',
    Sort: '',
    FlowType: props.flowType
  }).then((rsp) => {
    if (rsp.IsSuccess) {
      const { PageNo, TotalCount, TotalPage } = rsp.Data
      pagination.total = TotalCount
      formLabels.value =
        rsp.Data.Columns?.filter((val) => val.IsShow)?.map((v) => {
          const { Label, CanEdit, Category, IsShow, FlowTemplateNodeFormID, FlowTemplateNodeID } = v
          // let col: any = {
          //   field: Label,
          //   hide: !IsShow
          // };
          return {
            field: Label,
            headerName: Label,
            // cellRenderer: editComMap[Category] || "EInput",
            // cellRendererParams: { colProp: Label },
            // hide: !IsShow,
            FlowTemplateNodeFormID,
            FlowTemplateNodeID,
            Category,
          }
        }) || []
      let list = []
      JSON.parse(rsp.Data.Data)?.forEach((v) => {
        const {
          CurrentNodeId,
          MaxSort,
          KeyValuePairs,
          CurrentNodeSort,
          CurrentNodeName,
          FinishNode,
        } = v || {}
        const progressPercentage = FinishNode
          ? 100
          : Math.round(((CurrentNodeSort - 1) / MaxSort) * 100)
        let obj = {
          progressPercentage: progressPercentage,
          CurrentNodeId,
          CurrentNodeName,
          FinishNode,
        }
        let cellInfo = {}
        KeyValuePairs.forEach((val) => {
          const { CanEdit, FlowTemplateNodeFormID, FlowTemplateNodeID, Id, InstanceId, ...reset } =
            val
          const keys = Object.keys(reset)
          cellInfo[keys[0]] = {
            CanEdit,
            FlowTemplateNodeFormID,
            FlowTemplateNodeID,
            Id,
            InstanceId,
          }
          obj = { ...obj, ...reset, InstanceId }
        })
        list.push({ ...obj, cellInfo })
      })
      // formList.value = list;
      flowInstanceList.value = list
    } else {
      // message(rsp.ErrorMsg, { type: "error" });
      toast.error(rsp.ErrorMsg)
    }
  })
}

/** 跳转到详情界面 **/
const goToDetailPage = (formDataInfo) => {
  const canEditKeys =
    Object.keys(formDataInfo?.cellInfo || {}).filter((v) => {
      return formDataInfo.cellInfo?.[v]?.CanEdit
    }) || []
  const columns = formLabels.value?.filter((v) => canEditKeys.includes(v.field))
  if (!canEditKeys.length) {
    return toast.warning('当前没有可编辑的字段')
  }
  const formFieldInfo = columns?.map((v) => {
    const { Category, headerName, field } = v
    return {
      label: headerName,
      type: Category,
      value: formDataInfo?.[field],
      field,
      props:
        Category == 'Switch'
          ? {
              style: '--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949',
              'active-text': '是',
              'inactive-text': '否',
              'inline-prompt': true,
            }
          : '',
    }
  })
  uni.navigateTo({
    url: '/pages/detail/index',
    /*  events: {
      refershEvent: function(data) {
        getFlowInstancePages()
      }
    }, */
    success: function (res) {
      // 通过eventChannel向被打开页面传送数据
      res.eventChannel.emit('acceptDataFromOpenerPage', {
        formDataInfo,
        formLabels: formLabels.value,
        formFieldInfo,
      })
    },
  })
}

/**
 * @description: 进入页面刷新数据
 * @return {*}
 */
onShow(() => {
  getFlowInstancePages()
})

/**
 * @description: 选择查询条件
 * @param {*} val
 * @return {*}
 */
const menuclick = (val: any) => {
    queryForm.QueryLabel = val?.item?.content || '全部';
    queryForm.QueryValue = '';
} 

/**
 * @description: 初始化
 * @return {*}
 */
onMounted(() => {
  getFiterList()
})
</script>
<style scoped lang="scss">
.page {
  // height: 83vh;
  background-color: $uni-bg-color-hover;
  .mt12 {
    margin-top: 12rpx;
  }
  .mb12 {
    margin-bottom: 12rpx;
  }
  .search-type {
  position: relative;
  height: 30px;
  line-height: 30px;
  padding: 0 8px 0 8px;
}
}
.footer {
  text-align: left;
}
:deep(.wd-popover__menu) {
  position: absolute !important;
  left: -55rpx;
  height: 400rpx;
  overflow: auto;
}
</style>
